package com.mactivity.activities;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mactivity.database.CustomHttpClient;
import com.mactivity.database.NotificationActivityFunctions;
import com.mactivity.helper.Constants;
import com.mactivity.helper.Messages;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
 * Author Sanjay Vasudeva
 * Class NotificationGroupPlanActivity - handles viewing details of the Group Plans and accepting-rejecting them
 * */
public class NotificationGroupPlanActivity extends Activity {
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads().detectDiskWrites().detectNetwork() // or	.detectAll() for all detectable problems
		.penaltyLog().build());

		super.onCreate(savedInstanceState);
		setContentView(R.layout.notificationpost);

		Button accept,reject,delete;
		int groupplanid=0;
		int innotin=0;
		//get the buttons - accept,reject and OK. button
		accept = (Button) findViewById(R.id.buttonaccept);
		reject = (Button) findViewById(R.id.buttonreject);
		//delete is actually OK button
		delete = (Button) findViewById(R.id.buttonDelete);
		//Get the texts.
		TextView requestfromname = (TextView) findViewById(R.id.requestfromname);        
		TextView requestfromemail = (TextView) findViewById(R.id.requestfromemail);        
		TextView groupplansport = (TextView) findViewById(R.id.groupplansport);        
		TextView groupplansportlabel = (TextView) findViewById(R.id.groupplansportlabel);        
		TextView groupplandatelabel = (TextView) findViewById(R.id.groupplandatelabel);        
		TextView groupplantimelabel = (TextView) findViewById(R.id.groupplantimelabel);    
		//these fields are extracted for queries.So they must be final.
		final TextView groupplandate = (TextView) findViewById(R.id.groupplandate);        
		final TextView groupplantime = (TextView) findViewById(R.id.groupplantime);        
		final TextView planclash = (TextView) findViewById(R.id.planclash);        
		final TextView clasheAcceptedGPNoteId = (TextView) findViewById(R.id.clashAcceptedGPNoteId);        

		//Get the GroupPlanId to get the details
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			groupplanid = extras.getInt(Constants.COLUMN_NOTIFICATION_GROUPPLANID);
			innotin= extras.getInt(Constants.COLUMN_NOTIFICATION_TYPESTATUS);
		}
		Integer I=new Integer(groupplanid);
		String response = null;
		accept.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View arg0) {
				final int ACTIVITY_CREATE = 0;
				Bundle extras = getIntent().getExtras();
				int noteid,notefrom,noteto;
				String date,time;
				NotificationActivityFunctions notificationActivityFunctions=new NotificationActivityFunctions();
				//get the notification column details
				noteid=extras.getInt(Constants.COLUMN_NOTIFICATION_NOTEID);
				notefrom=extras.getInt(Constants.CONSTANT_EXTRAS_FROMID);
				noteto=extras.getInt(Constants.CONSTANT_EXTRAS_TOID);
				//If there is a clashed Group Plan which is already accepted. The clashed NoteId is saved in this and hidden. This NoteId's TypeStatus is then set to 3 to say its been rejected now
				String noteId=clasheAcceptedGPNoteId.getText().toString();
				//Check when Plan is clashing.
				String planClash=planclash.getText().toString();
				//get the date and time of the plan from screen
				date=groupplandate.getText().toString();   
				time=groupplantime.getText().toString(); 

				Integer N=new Integer(noteid);
				Integer F=new Integer(notefrom);
				Integer T=new Integer(noteto);
				Integer A=new Integer(2);
				
				try {
					//planClash!= ""  means there is a plan clashing already.
					//noteId == "" - here if NoteId is not set an IndividualPlan is clashing
					//Deleting the Individual Plan
					if(noteId == "" && planClash!=""){
						notificationActivityFunctions.deleteOldIP(date,time,T);
					}
					// Else the clashing is from a accepted group plan. Here we reject the old plan by changing TypeStatus for that NoteId
					else if(planClash != ""){
						notificationActivityFunctions.rejectOldAcceptedGP(noteId);
					}
					//In both cases above on accept the current plan should be accepted.
					//Change in the notification table. Set the NoteTo to NoteFrom and vice versa,for that NoteId. Set TypeStatus to 2.
					notificationActivityFunctions.acceptrejectGroupPlan(N, F, T, A);
					//Redirect to Notifications.
					Intent i = new Intent(NotificationGroupPlanActivity.this, NotificationActivity.class);
					startActivityForResult(i, ACTIVITY_CREATE);
					NotificationGroupPlanActivity.this.finish();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.e(Constants.LOGGER_ERROR_TAG,"Exception in NotificationGroupPlanActivity onClick Accept"+ e.getMessage());
				}
			}

		});

		reject.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				final int ACTIVITY_CREATE = 0;
				Bundle extras = getIntent().getExtras();
				int noteid,notefrom,noteto;
				noteid=extras.getInt(Constants.COLUMN_NOTIFICATION_NOTEID);
				notefrom=extras.getInt(Constants.CONSTANT_EXTRAS_FROMID);
				noteto=extras.getInt(Constants.CONSTANT_EXTRAS_TOID);
				Integer N=new Integer(noteid);
				Integer F=new Integer(notefrom);
				Integer T=new Integer(noteto);
				Integer A=new Integer(3);
				try {
					//Change in the notification table. Set the NoteTo to NoteFrom and vice versa,for that NoteId. Set TypeStatus to 3
					NotificationActivityFunctions notificationActivityFunctions=new NotificationActivityFunctions();
					notificationActivityFunctions.acceptrejectGroupPlan(N, F, T, A);
					//Redirect to Notifications.
					Intent i = new Intent(NotificationGroupPlanActivity.this, NotificationActivity.class);
					startActivityForResult(i, ACTIVITY_CREATE);
					NotificationGroupPlanActivity.this.finish();
				} catch (Exception e) {
					Log.e(Constants.LOGGER_ERROR_TAG,"Exception in NotificationGroupPlanActivity onClick Reject"+ e.getMessage());
				}
			}
		});

		delete.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				final int ACTIVITY_CREATE = 0;
				try {
					// redirect to Notifications board after clicking OK. button
					Intent i = new Intent(NotificationGroupPlanActivity.this, NotificationActivity.class);
					startActivityForResult(i, ACTIVITY_CREATE);
					NotificationGroupPlanActivity.this.finish();
				} catch (Exception e) {
					Log.e(Constants.LOGGER_ERROR_TAG,"Exception in NotificationGroupPlanActivity onClick OK button"+ e.getMessage());
				}
			}
		});
		try{
			//Get the plan details.
			NotificationActivityFunctions notificationActivityFunctions=new NotificationActivityFunctions();
			response = notificationActivityFunctions.getGroupPlanRequestDetails(I);
			try{
				JSONArray jArray = new JSONArray(response);
				for(int i=0;i<jArray.length();i++){
					JSONObject json_data = jArray.getJSONObject(i);
					//Get the plan details which is showed on screen
					String noteFrom=json_data.getString(Constants.JSON_STRING_NAME);
					String noteEmail=json_data.getString(Constants.JSON_STRING_EMAIL);
					String sport=json_data.getString(Constants.JSON_STRING_SPORT);
					String date=json_data.getString(Constants.JSON_STRING_DATE);
					String time=json_data.getString(Constants.JSON_STRING_TIME);
					//getting the NoteTo and NoteFrom values.
					//NoteTo here is the current user.NoteFrom is the user who accepted,rejected or sent a Group Plan request
					int noteto=extras.getInt(Constants.CONSTANT_EXTRAS_TOID);
    	            int notefrom=extras.getInt(Constants.CONSTANT_EXTRAS_FROMID);
    				//innotin == 1 means its a Group Plan request.
    	            if(innotin==1){
        				Integer T=new Integer(noteto);
        				String conflictMessage=null;
        				//Checking if the same date and time, for the user if there is already a plan existing
    					ArrayList<NameValuePair> postParametersConflict = new ArrayList<NameValuePair>();
    					postParametersConflict.add(new BasicNameValuePair(Constants.CONSTANT_EXTRAS_CLASH_DATE,date));
    					postParametersConflict.add(new BasicNameValuePair(Constants.CONSTANT_EXTRAS_CLASH_TIME,time));
    					postParametersConflict.add(new BasicNameValuePair(Constants.CONSTANT_EXTRAS_CLASH_USERID,T.toString()));
    					//response1 = 1 when there is already a group plan which the user has made himself at the same time and date
    					String response1 = CustomHttpClient.executeHttpPost("http://omega.uta.edu/~hbs1966/db_files/PlanActivity/check_group_time_conflict.php",postParametersConflict);
    					//response2 = 1 when there is already an Individual plan which the user has made himself at the same time and date
    					String response2 = CustomHttpClient.executeHttpPost("http://omega.uta.edu/~hbs1966/db_files/PlanActivity/check_individual_time_conflict.php",postParametersConflict);
    					//response3 = 1 when there is already a group plan which the user has accepted to be a part of at the same time and date
    					String response3 = CustomHttpClient.executeHttpPost("http://omega.uta.edu/~hbs1966/db_files/PlanActivity/check_accepted_group_conflict.php",postParametersConflict);

    					//set the details on the page
    					requestfromname.setText(noteFrom);
    					requestfromemail.setText(noteEmail);        
    					groupplansport.setText(sport) ;        
    					groupplandate.setText(date) ;        
    					groupplantime.setText(time) ;     
    					//Enable the Accept and Reject button. Hide OK button
    					groupplansportlabel.setVisibility(View.VISIBLE);        
    					groupplandatelabel.setVisibility(View.VISIBLE);        
    					groupplantimelabel.setVisibility(View.VISIBLE);   
    					delete.setVisibility(View.INVISIBLE);
    					//User made group plan exists - User cannot accept\reject this Plan
    					if (response1.contains("1")){
    						conflictMessage=Messages.NOTIFICATION_GROUPPLAN_CONFLICT_GROUPPLAN;
    						planclash.setText(conflictMessage);
    						planclash.setTypeface(null, Typeface.BOLD);
    						planclash.setTextColor(Color.parseColor("#FFFF00"));
    						//Hide the buttons for this case and not allow user to accept\reject
    						accept.setVisibility(View.INVISIBLE);
    						reject.setVisibility(View.INVISIBLE);
    					}
    					//User made an individual plan at the same time-date.User can accept\reject. On accept - the individual plan gets deleted
    					else if(response2.contains("1")){
    						conflictMessage=Messages.NOTIFICATION_GROUPPLAN_CONFLICT_INDIVIDUAL;
    						planclash.setText(conflictMessage);
    						planclash.setTypeface(null, Typeface.BOLD);
    						planclash.setTextColor(Color.parseColor("#FFFF00"));
    					}
    					//User already accepted a Group Plan at the same time-date. User can accept\reject. On accept - the old accepted group plan gets rejected.
    					else if(response3.contains("1")){
    						conflictMessage=Messages.NOTIFICATION_GROUPPLAN_CONFLICT_ACCEPTEDGROUPPLAN;
    						//Get the NoteId of the accepted group plan.
        					String response4 = notificationActivityFunctions.getNoteIDAcceptedGroupPlan(date,time,T);
        					JSONArray jArray4 = new JSONArray(response4);
        					JSONObject json_data4 = jArray4.getJSONObject(0);
        					String noteId=json_data4.getString(Constants.JSON_STRING_NOTEID);
        					//Keep the NoteId of the accepted Group plan in the screen and hide it.
        					clasheAcceptedGPNoteId.setText(noteId);
        					clasheAcceptedGPNoteId.setVisibility(View.INVISIBLE);
        					planclash.setText(conflictMessage);
    						planclash.setTypeface(null, Typeface.BOLD);
    						planclash.setTextColor(Color.parseColor("#FFFF00"));
    					}
    				}
					//If its just viewing an accepted request for a group plan, hide the accept\reject button and show OK button
					if(innotin==2 || innotin==3){
						Integer Id=new Integer(notefrom);
						String responseFriendDetails = null;
						responseFriendDetails = notificationActivityFunctions.fetchUserDetails(Id);
						JSONArray jArrayFriendDetails = new JSONArray(responseFriendDetails);
						for(i=0;i<jArrayFriendDetails.length();i++){
							JSONObject json_dataFriendDetails = jArrayFriendDetails.getJSONObject(i);
							noteFrom=json_dataFriendDetails.getString(Constants.JSON_STRING_NAME);
							noteEmail=json_dataFriendDetails.getString(Constants.JSON_STRING_EMAIL);
							groupplansport.setText(sport) ;        
							groupplandate.setText(date) ;        
							groupplantime.setText(time) ;        
							//show Name and email
							requestfromname.setText(noteFrom);
							requestfromemail.setText(noteEmail);        
						}
						accept.setVisibility(View.INVISIBLE);
						reject.setVisibility(View.INVISIBLE);
						delete.setVisibility(View.VISIBLE);
					}

				}

			}

			catch(JSONException e){
				Log.e("log_tag", "Error parsing data "+e.toString());
			}
		}
		catch(Exception e){
		}

	}
	@Override
	public void onBackPressed() {
		final int ACTIVITY_CREATE = 0;
		Intent i = new Intent(NotificationGroupPlanActivity.this, NotificationActivity.class);
		startActivityForResult(i, ACTIVITY_CREATE);
		NotificationGroupPlanActivity.this.finish();
	}
}
